import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { getOrders, saveForm, initData } from '../spider/index'
import dayjs from 'dayjs'
import { addLog } from '../spider/utils'
const fs = require('fs')
const cp = require('child_process')

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    title: '自动化下单',
    width: 1280,
    height: 800,
    show: false,
    resizable: false,
    autoHideMenuBar: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })
  // 插入方法
  ipcMain.on('set-title', (event, title) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.setTitle(title)
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // 启动浏览器
  cp.exec(
    'chrome.exe --remote-debugging-port=9223 --user-data-dir="C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data"',
    (err) => {
      if (err) {
        console.log('浏览器启动失败了')
      }
    }
  )

  // 执行后台方法
  ipcMain.handle('run', (event, orders) => {
    addLog({
      type: 'run',
      data: orders,
      time: dayjs().format('YYYY-MM-DD HH:mm:ss')
    })
    // 获取订单号
    getOrders(orders)
  })

  // 执行后台方法
  ipcMain.handle('save', (event, value) => {
    let list = JSON.parse(value)

    addLog({
      type: 'save',
      data: list,
      time: dayjs().format('YYYY-MM-DD HH:mm:ss')
    })
    // 获取订单号
    saveForm(list)
  })

  // 初始化数据
  ipcMain.handle('init-data', (event) => {
    let data = initData()
    // 获取到数据后返回给前端
    return data
  })

  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
// 日志

//安装完成后自动生成文件夹
fs.mkdir('c://appData', (err) => console.log(err))
fs.mkdir('c://appData/log', (err) => console.log(err))
fs.mkdir('c://appData/save', (err) => console.log(err))

if (!fs.existsSync('c://appData/log/log.json')) {
  fs.open('c://appData/log/log.json', 'w+', (err) => {
    if (err) {
      console.log('err', err)
    } else {
      console.log('创建成功')
    }
  })
}

if (!fs.existsSync('c://appData/save/save.json')) {
  fs.open('c://appData/save/save.json', 'w+', (err) => {
    if (err) {
      console.log('err', err)
    } else {
      console.log('创建成功')
    }
  })
}
